package s;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.List;

/**
 * Created by luogui on 2016/12/30.
 */

public class GsonUtil
{

	public static Gson getGson()
	{
		return new GsonBuilder().serializeNulls().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
				.create();
	}

	public static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory
	{
		@SuppressWarnings("unchecked")
		public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
		{
			Class<T> rawType = (Class<T>) type.getRawType();
			if (rawType != String.class)
			{
				return null;
			}
			return (TypeAdapter<T>) new StringNullAdapter();
		}
	}

	public static class StringNullAdapter extends TypeAdapter<String>
	{
		@Override
		public String read(JsonReader reader) throws IOException
		{
			if (reader.peek() == JsonToken.NULL)
			{
				reader.nextNull();
				return "";
			}
			return reader.nextString();
		}

		@Override
		public void write(JsonWriter writer, String value) throws IOException
		{
			if (value == null)
			{
				writer.nullValue();
				return;
			}
			writer.value(value);
		}
	}
}
